package cn.wowjoy.pda.android_pharmacy.model.xml;

import android.util.Log;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xml.sax.InputSource;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import cn.wowjoy.pda.android_pharmacy.model.xmlBaseRequest.RoleInfoBaseRequest;
import cn.wowjoy.pda.android_pharmacy.model.xmlBaseRequest.RoleInfoRequestBody;
import cn.wowjoy.pda.android_pharmacy.model.xmlBaseRequest.RoleInfoRequestEnvelope;
import cn.wowjoy.pda.android_pharmacy.model.xmlEntity.doorPatientInfo.DoorPatientInfoBeen;
import cn.wowjoy.pda.android_pharmacy.model.xmlEntity.employeeInfo.EmployeeInfoBeen;
import cn.wowjoy.pda.android_pharmacy.model.xmlEntity.inHospitalPatientInfo.InHospitalPatientBeen;
import cn.wowjoy.pda.android_pharmacy.model.xmlEntity.inHospitalPatientInfo.InHospitalPillSingleBeen;
import cn.wowjoy.pda.android_pharmacy.model.xmlEntity.inHospitalPatientInfo.InHospitalPillTotalBeen;
import cn.wowjoy.pda.android_pharmacy.model.xmlEntity.putInfo.PutSingleBeen;
import cn.wowjoy.pda.android_pharmacy.model.xmlEntity.putInfo.PutTotalBeen;
import cn.wowjoy.pda.android_pharmacy.model.xmlEntity.quey.QueryBeen;
import cn.wowjoy.pda.android_pharmacy.model.xmlEntity.staticPatientInfo.StaticSendBeen;

/**
 * Created by sinyo on 2017/7/27.
 */

public class XmlUtils {
    public static  RoleInfoRequestEnvelope prepare(String content){
        RoleInfoRequestEnvelope requestEnvelope = new RoleInfoRequestEnvelope();    //soapenv:Envelope
        RoleInfoRequestBody requestBody = new RoleInfoRequestBody();    // body
        RoleInfoBaseRequest baseRequest = new RoleInfoBaseRequest();    // getroleinfo
        baseRequest.content = content;
        baseRequest.NameAttribute = "http://tempuri.org/";
        requestBody.getroleinfo = baseRequest;
        requestEnvelope.body = requestBody;
        return requestEnvelope;
    }



    public static String xmlChangeString(String fileName) {
        try {
            SAXReader saxReader = new SAXReader();//新建一个解析类
            Document tempDocument = saxReader.read(XmlUtils.class.getClassLoader().getResourceAsStream(fileName));//读入一个文件
            return tempDocument.asXML();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }
    //将字符串string类型转换成xml文件
    public static void strChangeXML(String str) throws IOException {
        SAXReader saxReader = new SAXReader();
        Document document;
        try {
            document = saxReader.read(new ByteArrayInputStream(str.getBytes("UTF-8")));
            OutputFormat format = OutputFormat.createPrettyPrint();
            /** 将document中的内容写入文件中 */
            XMLWriter writer = new XMLWriter(new FileWriter(new File("src/com/webdesk/swing/powertable/digester/cctv.xml")), format);
            writer.write(document);
            writer.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
    /**
     * json 数据转换对象
     *
     * @param rootElt
     *            要转换的Element数据
     * @param pojo
     *            要转换的目标对象类型
     * @return 转换的目标对象
     * @throws Exception
     *             转换失败
     */
    @SuppressWarnings("rawtypes")
    public static Object fromXmlToBean(Element rootElt, Class pojo) throws Exception
    {
        // 首先得到pojo所定义的字段
        Field[] fields = pojo.getDeclaredFields();
        // 根据传入的Class动态生成pojo对象
        Object obj = pojo.newInstance();
        for (Field field : fields)
        {
            // 设置字段可访问（必须，否则报错）
            field.setAccessible(true);
            // 得到字段的属性名
            String name = field.getName();
            // 这一段的作用是如果字段在Element中不存在会抛出异常，如果出异常，则跳过。
            try
            {
                rootElt.elementTextTrim(name);
            }
            catch (Exception ex)
            {
                continue;
            }
            if (rootElt.elementTextTrim(name) != null && !"".equals(rootElt.elementTextTrim(name)))
            {
                // 根据字段的类型将值转化为相应的类型，并设置到生成的对象中。
                if (field.getType().equals(Long.class) || field.getType().equals(long.class))
                {
                    field.set(obj, Long.parseLong(rootElt.elementTextTrim(name)));
                }
                else if (field.getType().equals(String.class))
                {
                    field.set(obj, rootElt.elementTextTrim(name));
                }
                else if (field.getType().equals(Double.class) || field.getType().equals(double.class))
                {
                    field.set(obj, Double.parseDouble(rootElt.elementTextTrim(name)));
                }
                else if (field.getType().equals(Integer.class) || field.getType().equals(int.class))
                {
                    field.set(obj, Integer.parseInt(rootElt.elementTextTrim(name)));
                }
                else if (field.getType().equals(java.util.Date.class))
                {
                    field.set(obj, Date.parse(rootElt.elementTextTrim(name)));
                }
                else
                {
                    continue;
                }
            }
        }
        return obj;
    }
    /**
     * 把xml转化为DoorPatientInfoBeen集合
     *
     * @param xml
     * @return
     */
    public static List<InHospitalPillSingleBeen> getInHospitalPillSingleBeenList(String xml) {

        Document doc = null;
        List<InHospitalPillSingleBeen> list = new ArrayList<InHospitalPillSingleBeen>();
        try {
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML

            Element rootElt = doc.getRootElement(); // 获取根节点

            Element head = rootElt.element("head");
            if(!"0".equals(head.elementTextTrim("ErrCode"))){
                return null;
            }
            Element body = rootElt.element("body");
            Iterator<Element> it = body.elementIterator("DETAIL");// 获取根节点下所有content
            while (it.hasNext()) {
                Element elementGroupService = (Element) it.next();
                InHospitalPillSingleBeen baseBean = (InHospitalPillSingleBeen) XmlUtils.fromXmlToBean(
                        elementGroupService, InHospitalPillSingleBeen.class);
                list.add(baseBean);
            }
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("数据解析错误");
        }
        return list;
    }


    /**
     * 把xml转化为单个person
     *
     * @param xml
     * @return
     */
    public static QueryBeen getQueryBeen(String xml) {
        QueryBeen queryBeen = null;
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML

            Element rootElt = doc.getRootElement(); // 获取根节点

            System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称
            Element head = rootElt.element("head");
            if(!"0".equals(head.elementTextTrim("ErrCode"))){
                Log.e("PXY", "getDoorPatientInfoBeenList: "+"后台数据有问题" );
                return null;
            }
            Element body = rootElt.element("body");
            Element detail = body.element("DETAIL");
            queryBeen = (QueryBeen) XmlUtils.fromXmlToBean(
                    detail, QueryBeen.class);
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("数据解析错误");
        }
        return queryBeen;
    }

    /**
     * 把xml格式转化为person对象
     *
     * @param xml
     * @return
     */
    public static DoorPatientInfoBeen getDoorPatientInfoBeen(String xml) {
        DoorPatientInfoBeen person = null;
        InputSource in = new InputSource(new StringReader(xml));
        in.setEncoding("UTF-8");
        SAXReader reader = new SAXReader();
        Document document;
        try {
            document = reader.read(in);
            Element root = document.getRootElement();
            person = (DoorPatientInfoBeen) XmlUtils.fromXmlToBean(root, DoorPatientInfoBeen.class);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("数据解析错误");

        }
        return person;
    }


    /**
     * 把xml转化为DoorPatientInfoBeen集合
     *
     * @param xml
     * @return
     */
    public static List<InHospitalPatientBeen> getInHospitalPatientBeenList(String xml) {

        Document doc = null;
        List<InHospitalPatientBeen> list = new ArrayList<InHospitalPatientBeen>();
        try {
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML

            Element rootElt = doc.getRootElement(); // 获取根节点

            System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称
            Element head = rootElt.element("head");
            if(!"0".equals(head.elementTextTrim("ErrCode"))){
//                Log.e("PXY", "getDoorPatientInfoBeenList: "+"后台数据有问题" );
                return null;
            }
            Element body = rootElt.element("body");
            Iterator<Element> it = body.elementIterator("DETAIL");// 获取根节点下所有content
            while (it.hasNext()) {
                Element elementGroupService = (Element) it.next();
                InHospitalPatientBeen baseBean = (InHospitalPatientBeen) XmlUtils.fromXmlToBean(
                        elementGroupService, InHospitalPatientBeen.class);
                list.add(baseBean);
            }
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("数据解析错误");
        }
        return list;
    }
    /**
     * 把xml转化为DoorPatientInfoBeen集合
     *
     * @param xml
     * @return
     */
    public static List<PutTotalBeen> getPutTotalBeenList(String xml) {

        Document doc = null;
        List<PutTotalBeen> list = new ArrayList<PutTotalBeen>();
        try {
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML

            Element rootElt = doc.getRootElement(); // 获取根节点

            System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称
            Element head = rootElt.element("head");
            if(!"0".equals(head.elementTextTrim("ErrCode"))){
//                Log.e("PXY", "getPutTotalBeenList: "+"后台数据有问题" );
                return null;
            }
            Element body = rootElt.element("body");
            Iterator<Element> it = body.elementIterator("DETAIL");// 获取根节点下所有content
            while (it.hasNext()) {
                Element elementGroupService = (Element) it.next();
                PutTotalBeen baseBean = (PutTotalBeen) XmlUtils.fromXmlToBean(
                        elementGroupService, PutTotalBeen.class);
                list.add(baseBean);
            }
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("数据解析错误");
        }
        return list;
    }
    /**
     * 把xml转化为DoorPatientInfoBeen集合
     *
     * @param xml
     * @return
     */
    public static List<PutSingleBeen> getPutSingleBeenList(String xml) {

        Document doc = null;
        List<PutSingleBeen> list = new ArrayList<PutSingleBeen>();
        try {
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML

            Element rootElt = doc.getRootElement(); // 获取根节点

            System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称
            Element head = rootElt.element("head");
//            Log.e("PXY", "head : "+ head.getName() );
//            Log.e("PXY","ErrCode: "+head.elementTextTrim("ErrCode")+"  ErrMsg:"+head.elementTextTrim("ErrMsg"));
            if(!"0".equals(head.elementTextTrim("ErrCode"))){
//                Log.e("PXY", "getPutSingleBeenList: "+"后台数据有问题" );
                return null;
            }
            Element body = rootElt.element("body");
//            Log.e("PXY", "body : "+ body.getName() );
            Iterator<Element> it = body.elementIterator("DETAIL");// 获取根节点下所有content
            while (it.hasNext()) {
                Element elementGroupService = (Element) it.next();
                PutSingleBeen baseBean = (PutSingleBeen) XmlUtils.fromXmlToBean(
                        elementGroupService, PutSingleBeen.class);
                list.add(baseBean);
            }
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("数据解析错误");
        }
        return list;
    }
    /**
     * 把xml转化为DoorPatientInfoBeen集合
     *
     * @param xml
     * @return
     */
    public static List<InHospitalPillTotalBeen> getInHospitalPillBeenList(String xml) {

        Document doc = null;
        List<InHospitalPillTotalBeen> list = new ArrayList<InHospitalPillTotalBeen>();
        try {
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML

            Element rootElt = doc.getRootElement(); // 获取根节点

            System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称
            Element head = rootElt.element("head");
//            Log.e("PXY", "head : "+ head.getName() );
//            Log.e("PXY","ErrCode: "+head.elementTextTrim("ErrCode")+"  ErrMsg:"+head.elementTextTrim("ErrMsg"));
            if(!"0".equals(head.elementTextTrim("ErrCode"))){
                Log.e("PXY", "getPutSingleBeenList: "+"后台数据有问题" );
                return null;
            }
            Element body = rootElt.element("body");
//            Log.e("PXY", "body : "+ body.getName() );
            Iterator<Element> it = body.elementIterator("DETAIL");// 获取根节点下所有content
            while (it.hasNext()) {
                Element elementGroupService = (Element) it.next();
                InHospitalPillTotalBeen baseBean = (InHospitalPillTotalBeen) XmlUtils.fromXmlToBean(
                        elementGroupService, InHospitalPillTotalBeen.class);
                list.add(baseBean);
            }
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("数据解析错误");
        }
        return list;
    }
    public static String getErroMsg(String xml) {
        Document doc = null;
        List<DoorPatientInfoBeen> list = new ArrayList<DoorPatientInfoBeen>();
        try {
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML

            Element rootElt = doc.getRootElement(); // 获取根节点

            System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称
            Element head = rootElt.element("head");
//            Log.e("PXY", "head : "+ head.getName() );
//            Log.e("PXY","ErrCode: "+head.elementTextTrim("ErrCode")+"  ErrMsg:"+head.elementTextTrim("ErrMsg"));
            if (!"0".equals(head.elementTextTrim("ErrCode"))) {
//                Log.e("PXY", "getDoorPatientInfoBeenList: " + "后台数据有问题");
                return head.elementTextTrim("ErrMsg");
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }
        /**
     * 把xml转化为DoorPatientInfoBeen集合
     *
     * @param xml
     * @return
     */
    public static List<DoorPatientInfoBeen> getDoorPatientInfoBeenList(String xml) {

        Document doc = null;
        List<DoorPatientInfoBeen> list = new ArrayList<DoorPatientInfoBeen>();
        try {
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML

            Element rootElt = doc.getRootElement(); // 获取根节点

            System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称
            Element head = rootElt.element("head");
//            Log.e("PXY", "head : "+ head.getName() );
//            Log.e("PXY","ErrCode: "+head.elementTextTrim("ErrCode")+"  ErrMsg:"+head.elementTextTrim("ErrMsg"));
            if(!"0".equals(head.elementTextTrim("ErrCode"))){
                Log.e("PXY", "getDoorPatientInfoBeenList: "+"后台数据有问题" );
                return null;
            }
            Element body = rootElt.element("body");
            Log.e("PXY", "body : "+ body.getName() );
            Iterator<Element> it = body.elementIterator("DETAIL");// 获取根节点下所有content
            while (it.hasNext()) {
                Element elementGroupService = (Element) it.next();
                DoorPatientInfoBeen baseBean = (DoorPatientInfoBeen) XmlUtils.fromXmlToBean(
                        elementGroupService, DoorPatientInfoBeen.class);
                list.add(baseBean);
            }
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("数据解析错误");
        }
        return list;
    }
    /**
     * 把xml转化为单个person
     *
     * @param xml
     * @return
     */
    public static EmployeeInfoBeen getEmployeeInfoBeen(String xml) {
        EmployeeInfoBeen employeeInfoBeen = null;
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML

            Element rootElt = doc.getRootElement(); // 获取根节点

            System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称
            Element head = rootElt.element("head");
            if(!"0".equals(head.elementTextTrim("ErrCode"))){
                Log.e("PXY", "getDoorPatientInfoBeenList: "+"后台数据有问题" );
                return null;
            }
            Element body = rootElt.element("body");
            Element detail = body.element("DETAIL");
            employeeInfoBeen = (EmployeeInfoBeen) XmlUtils.fromXmlToBean(
                    detail, EmployeeInfoBeen.class);
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("数据解析错误");
        }
        return employeeInfoBeen;
    }
    /**
     * 把xml转化为单个person
     *
     * @param xml
     * @return
     */
    public static StaticSendBeen getStaticSendBeen(String xml) {
        StaticSendBeen employeeInfoBeen = null;
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML

            Element rootElt = doc.getRootElement(); // 获取根节点

//            System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称
            Element head = rootElt.element("head");
            if(!"0".equals(head.elementTextTrim("ErrCode"))){
                Log.e("PXY", "getDoorPatientInfoBeenList: "+"后台数据有问题" );
                return null;
            }
            Element body = rootElt.element("body");
            Element detail = body.element("DETAIL");
            employeeInfoBeen = (StaticSendBeen) XmlUtils.fromXmlToBean(
                    detail, StaticSendBeen.class);
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("数据解析错误");
        }
        return employeeInfoBeen;
    }
    /**
     * 把xml转化为person集合
     *
     * @param xml
     * @return
     */
    public static List<EmployeeInfoBeen> getEmployeeInfoBeenList(String xml) {

        Document doc = null;
        List<EmployeeInfoBeen> list = new ArrayList<EmployeeInfoBeen>();
        try {
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML

            Element rootElt = doc.getRootElement(); // 获取根节点

            System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称
            Element head = rootElt.element("head");
//            Log.e("PXY", "head : "+ head.getName() );
//            Log.e("PXY","ErrCode: "+head.elementTextTrim("ErrCode")+"  ErrMsg:"+head.elementTextTrim("ErrMsg"));
            if(!"0".equals(head.elementTextTrim("ErrCode"))){
                Log.e("PXY", "getDoorPatientInfoBeenList: "+"后台数据有问题" );
                return null;
            }
            Element body = rootElt.element("body");
//            Log.e("PXY", "body : "+ body.getName() );
            Iterator<Element> it = body.elementIterator("DETAIL");// 获取根节点下所有content
            while (it.hasNext()) {
                    Element elementGroupService = (Element) it.next();
                    EmployeeInfoBeen baseBean = (EmployeeInfoBeen) XmlUtils.fromXmlToBean(
                        elementGroupService, EmployeeInfoBeen.class);
                list.add(baseBean);
            }
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("数据解析错误");
        }
        return list;
    }
    /**
     * 更新
     *
     * @param xml
     * @return
     */
    public static boolean updateResult(String xml) {

        Document doc = null;

        try {
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML

            Element rootElt = doc.getRootElement(); // 获取根节点

            System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称
            Element head = rootElt.element("head");
//            Log.e("PXY", "head : "+ head.getName() );
//            Log.e("PXY","ErrCode: "+head.elementTextTrim("ErrCode")+"  ErrMsg:"+head.elementTextTrim("ErrMsg"));
            if("0".equals(head.elementTextTrim("ErrCode"))){
                return true;
            }
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("数据解析错误");
        }
        return false;
    }
    /**
     * 把xml转化为person集合
     *
     * @param xml
     * @return
     */
    public static String getPendingNum(String xml) {

        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML

            Element rootElt = doc.getRootElement(); // 获取根节点

//            System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称
            Element head = rootElt.element("head");
//            Log.e("PXY", "head : "+ head.getName() );
//            Log.e("PXY","ErrCode: "+head.elementTextTrim("ErrCode")+"  ErrMsg:"+head.elementTextTrim("ErrMsg"));
            if(!"0".equals(head.elementTextTrim("ErrCode"))){
                Log.e("PXY", "getDoorPatientInfoBeenList: "+"后台数据有问题" );
                return null;
            }
            Element body = rootElt.element("body");
//            Log.e("PXY", "body : "+ body.getName() );
            Element detail = body.element("DETAIL");
            return  detail.elementTextTrim("CXFHSL");

        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("数据解析错误");
        }
        return null;
    }
}
